//package top.suven.base.core.httpclient;
//
//import top.suven.base.util.monitor.MetricHelper;
//import com.codahale.metrics.httpclient.InstrumentedHttpClientConnectionManager;
//import com.dianping.cat.Cat;
//import com.dianping.cat.CatConstants;
//import com.dianping.cat.common.CatContext;
//import com.dianping.cat.common.ContextSession;
//import com.dianping.cat.message.Transaction;
//import org.apache.http.Header;
//import org.apache.http.HttpRequestInterceptor;
//import org.apache.http.NameValuePair;
//import org.apache.http.StatusLine;
//import org.apache.http.client.config.RequestConfig;
//import org.apache.http.client.entity.UrlEncodedFormEntity;
//import org.apache.http.client.methods.CloseableHttpResponse;
//import org.apache.http.client.methods.HttpGet;
//import org.apache.http.client.methods.HttpPost;
//import org.apache.http.client.methods.HttpUriRequest;
//import org.apache.http.entity.ContentType;
//import org.apache.http.entity.StringEntity;
//import org.apache.http.impl.client.CloseableHttpClient;
//import org.apache.http.impl.client.HttpClientBuilder;
//import org.apache.http.impl.client.HttpClients;
//import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
//import org.apache.http.util.EntityUtils;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.beans.factory.InitializingBean;
//
//import java.io.IOException;
//import java.io.UnsupportedEncodingException;
//import java.util.List;
//import top.suven.base.util.constants.Env;
//
//
//public class HttpService implements InitializingBean {
//    private Logger logger = LoggerFactory.getLogger(getClass());
//    private CloseableHttpClient client;
//
//    private int readTimeout;
//    private int connectTimeout;
//
//    private int maxTotal = 128 ;
//
//    private int defaultMaxPerRoute = 128 ;
//
//    public void setReadTimeout(int readTimeout) {
//        this.readTimeout = readTimeout;
//    }
//
//    public void setConnectTimeout(int connectTimeout) {
//        this.connectTimeout = connectTimeout;
//    }
//
//    public void setMaxTotal(int maxTotal) {
//		this.maxTotal = maxTotal;
//	}
//
//	public void setDefaultMaxPerRoute(int defaultMaxPerRoute) {
//		this.defaultMaxPerRoute = defaultMaxPerRoute;
//	}
//
//	public CloseableHttpClient getClient() {
//        return client;
//    }
//
//    @Override
//    public void afterPropertiesSet() {
//        PoolingHttpClientConnectionManager connectionManager = new InstrumentedHttpClientConnectionManager(MetricHelper.getMetric());
//        connectionManager.setMaxTotal(maxTotal);
//        connectionManager.setDefaultMaxPerRoute(defaultMaxPerRoute);
//        if(readTimeout <=0){
//            readTimeout = 5000 ;
//        }
//        if(connectTimeout <=0){
//            connectTimeout = 1000 ;
//        }
//        RequestConfig config = RequestConfig.custom().setConnectionRequestTimeout(1000).setConnectTimeout(connectTimeout).setSocketTimeout(readTimeout).build();
//
//        HttpClientBuilder builder = HttpClients.custom().setConnectionManager(connectionManager).setDefaultRequestConfig(config);
//
//
//        HttpRequestInterceptor interceptor = new CatRequestInterceptor() ;
//        builder.addInterceptorFirst(interceptor) ;
//
//        client = builder.build();
//    }
//
//
//    /**
//     *
//     * @param request
//     * @param urlForCat
//	 * @return
//     */
//    public Response execute(HttpUriRequest request , String urlForCat) {
//		CloseableHttpResponse httpResponse = null ;
//		Response response = null ;
//
//		int index = urlForCat.indexOf("?") ;
//		if(index != -1){
//			urlForCat = urlForCat.substring(0 , index) ;
//		}
//
//		Transaction t = Cat.newTransaction(CatConstants.TYPE_URL,  urlForCat);
//
//		buildContext() ;
//
//		try {
//
//			httpResponse =   client.execute(request);
//			StatusLine statusLine = httpResponse.getStatusLine() ;
//			response = new Response();
//			response.setCode(statusLine.getStatusCode());
//			response.setBody(EntityUtils.toString(httpResponse.getEntity()));
//			Header [] headers = httpResponse.getAllHeaders() ;
//			if(headers != null){
//				for(Header header : headers){
//					response.putHeader(header.getName(), header.getValue());
//				}
//			}
//			t.setStatus(Transaction.SUCCESS);
//		} catch (IOException e) {
//			t.setStatus(e);
//			t.addData("args", request.getRequestLine());
//			logger.error("http request throw IOException , url :{} " , request.getURI().getPath() , e);
//		}catch (Exception e) {
//			t.setStatus(e);
//			logger.error("http request error url :{} " , request.getURI().getPath() , e);
//		}
//		finally{
//			if(httpResponse != null){
//				try {
//					httpResponse.close();
//				} catch (IOException e) {
//					logger.error("httpResponse close error " , e);
//				}
//			}
//			t.complete();
//		}
//		return response ;
//	}
//
//
//
//	public  Response  post(String url , List<NameValuePair> nameValuePairs){
//		HttpPost httpPost = new HttpPost(url) ;
//
//		if(nameValuePairs != null && ! nameValuePairs.isEmpty()){
//			UrlEncodedFormEntity uefEntity;
//			try {
//				uefEntity = new UrlEncodedFormEntity(nameValuePairs,"UTF-8");
//				httpPost.setEntity(uefEntity);
//			} catch (UnsupportedEncodingException e) {
//				logger.error("UnsupportedEncodingException ");
//				return null ;
//			}
//		}
//		return execute(httpPost , url) ;
//	}
//
//	public  Response  post(String url , List<NameValuePair> nameValuePairs , int timeout){
//		HttpPost httpPost = new HttpPost(url) ;
//
//		RequestConfig requestConfig = RequestConfig.custom()
//                .setSocketTimeout(timeout).build();
//		httpPost.setConfig(requestConfig);
//
//		if(nameValuePairs != null && ! nameValuePairs.isEmpty()){
//			UrlEncodedFormEntity uefEntity;
//			try {
//				uefEntity = new UrlEncodedFormEntity(nameValuePairs,"UTF-8");
//				httpPost.setEntity(uefEntity);
//			} catch (UnsupportedEncodingException e) {
//				logger.error("UnsupportedEncodingException ");
//				return null ;
//			}
//		}
//		return execute(httpPost , url) ;
//	}
//
//	public  Response postJson(String url , String body){
//		HttpPost httpPost = new HttpPost(url) ;
//		StringEntity stringEntity = new StringEntity(body , ContentType.APPLICATION_JSON) ;
//		httpPost.setHeader("Content-type", "application/json");
//		httpPost.setEntity(stringEntity);
//		return execute(httpPost , url)  ;
//	}
//
//	public  Response postJson(String url , String body , int timeout){
//		HttpPost httpPost = new HttpPost(url) ;
//
//		RequestConfig requestConfig = RequestConfig.custom()
//                .setSocketTimeout(timeout).build();
//		httpPost.setConfig(requestConfig);
//
//		StringEntity stringEntity = new StringEntity(body , ContentType.APPLICATION_JSON) ;
//		httpPost.setHeader("Content-type", "application/json");
//		httpPost.setEntity(stringEntity);
//		return execute(httpPost , url)  ;
//	}
//
//
//	public  Response postThrift(String url , String body){
//		HttpPost httpPost = new HttpPost(url) ;
//		StringEntity stringEntity = new StringEntity(body , ContentType.APPLICATION_JSON) ;
//		httpPost.setHeader("Content-type", "application/json");
//		httpPost.setHeader("protocol", "json");
//		httpPost.setEntity(stringEntity);
//		return execute(httpPost , url)   ;
//	}
//
//
//	public  Response postThrift(String url , String body , int timeout){
//		HttpPost httpPost = new HttpPost(url) ;
//		RequestConfig requestConfig = RequestConfig.custom()
//                .setSocketTimeout(timeout).build();//
//		httpPost.setConfig(requestConfig);
//		StringEntity stringEntity = new StringEntity(body , ContentType.APPLICATION_JSON) ;
//		httpPost.setHeader("Content-type", "application/thrift");
//		httpPost.setHeader("protocol", "json");
//		httpPost.setEntity(stringEntity);
//		return execute(httpPost , url)   ;
//	}
//
//	public  Response get(String url){
//		HttpGet httpGet = new HttpGet(url) ;
//		return execute(httpGet , url) ;
//	}
//
//	/**
//	 *
//	 * @param url
//	 * @param timeout   ms
//	 * @return
//	 */
//	public  Response get(String url , int timeout){
//		HttpGet httpGet = new HttpGet(url) ;
//		RequestConfig requestConfig = RequestConfig.custom()
//                .setSocketTimeout(timeout).build();
//        httpGet.setConfig(requestConfig);
//		return execute(httpGet , url) ;
//	}
//
//
//	public  Response getRestful(String url , String urlForCat){
//		HttpGet httpGet = new HttpGet(url) ;
//		return execute(httpGet  , urlForCat) ;
//	}
//
//	/**
//	 *
//	 * @param url  http://host:port/123
//	 * @param urlForCat  http://host:port/
//	 * @param timeout ms
//	 * @return
//	 */
//	public  Response getRestful(String url , String urlForCat , int timeout){
//		HttpGet httpGet = new HttpGet(url) ;
//		RequestConfig requestConfig = RequestConfig.custom()
//                .setSocketTimeout(timeout).build();
//		httpGet.setConfig(requestConfig);
//		return execute(httpGet  , urlForCat) ;
//	}
//
//    public static void main(String[] args) {
//        HttpService httpService = new HttpService();
//        httpService.afterPropertiesSet();
//        System.out.println(httpService.get("http://www.kugou.com"));
//    }
//
////    private void buildContext() {
////		CatContext context = new CatContext();
////    	context.setClientName(Cat.getManager().getDomain());
////    	String ip = Env.getServerName() ;
////    	if(Cat.getManager().getThreadLocalMessageTree() != null){
////    		ip = Cat.getManager().getThreadLocalMessageTree().getIpAddress() ;
////    	}
////    	context.setClientIp(ip);
////    	Cat.logRemoteCallClient(context);
////    	ContextSession.put(context.pack());
////	}
//
//}
